package com.fc.utils;

import org.apache.commons.lang.StringUtils;
import java.util.regex.Pattern;

/**
 * 脱敏工具类
 */
public class DesensitizeUtil {

    /* 预编译正则表达式（提升性能） */
    private static final Pattern PHONE_PATTERN = Pattern.compile("(\\d{3})\\d{4}(\\d{4})");
    private static final Pattern EMAIL_PATTERN = Pattern.compile("(^.)[^@]*(@.*$)");
    private static final Pattern ID_CARD_PATTERN = Pattern.compile("(\\d{4})\\d{10}(\\w{4})");

    /**
     * 中文姓名：张三 → 张*
     */
    public static String hideName(String name) {
        if (StringUtils.isBlank(name)) return name;
        return name.charAt(0) + "*".repeat(Math.max(0, name.length() - 1));
    }

    /**
     * 手机号：13812345678 → 138****5678
     */
    public static String hidePhone(String phone) {
        if (StringUtils.isBlank(phone)) return phone;
        return PHONE_PATTERN.matcher(phone).replaceFirst("$1****$2");
    }

    /**
     * 邮箱：zhangsan@163.com → z****@163.com
     */
    public static String hideEmail(String email) {
        if (StringUtils.isBlank(email)) return email;
        return EMAIL_PATTERN.matcher(email).replaceFirst("$1****$2");
    }

    /**
     * 身份证：123456789012345678 → 1234****5678
     */
    public static String hideIdCard(String idCard) {
        if (StringUtils.isBlank(idCard)) return idCard;
        return ID_CARD_PATTERN.matcher(idCard).replaceFirst("$1****$2");
    }

    /**
     * 通用脱敏：保留前后指定长度，中间用符号填充
     */
    public static String customMask(String origin, int prefix, int suffix, String mask) {
        if (origin == null || origin.isEmpty()) return origin;
        int len = origin.length();
        if (prefix + suffix >= len) return origin; // 不脱敏

        String prefixStr = origin.substring(0, prefix);
        String suffixStr = origin.substring(len - suffix);
        String masked = mask.repeat(len - prefix - suffix);
        return prefixStr + masked + suffixStr;
    }
}